#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int ret = 0;
    void dfs(vector<string>& words, unordered_map<char, int>& hash, vector<int>& score, int n, int cur)
    {
        //cout << cur << ' ' << n << endl;
        if (n == words.size()) {
            ret = max(ret, cur);
            return;
        }

        vector<int> wordnum(26);
        for (auto ch : words[n]) wordnum[ch - 'a']++;
        int sco = 0;
        int i = 0;
        for (; i < 26; i++)
        {
            if (hash[i + 'a'] < wordnum[i]) break;
            hash[i + 'a'] -= wordnum[i];
            sco += wordnum[i] * score[i];
        }
        if (i == 26) dfs(words, hash, score, n + 1, cur + sco);
        for (int j = 0; j < i; j++) hash[j + 'a'] += wordnum[j];

        dfs(words, hash, score, n + 1, cur);
    }

    int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score) {
        unordered_map<char, int> hash;
        for (auto ch : letters) hash[ch]++;
        dfs(words, hash, score, 0, 0);
        return ret;
    }
};